qui(function(require, exports, module) {
    Sginal.Edit = function(options) {
        this.dao = Sginal.Dao;
        this.options = $.extend(true, {}, options);

        this.util = Sginal.Util || {};
        this.config = Sginal.config || {};
    };

    Sginal.Edit.prototype = {
        initConfig: function() {
			return true;
		},
        init: function() {
        },

        run: function() {
            var self = this;
            var $container = self.options.$container;
            self.init();
            self.initConfig();

			self.bindEvent();
			self.perpareData();
            self.fillForm();
            self.initSuggest();
        },

        perpareData: function() {
            var self = this;
            var username = $("div.user a.name").html();
        },

        fillForm: function () {
            var id = Sginal.Util.getUrlId("id");
            var self = this;
            if (id != null) {
                self.dao.getList({id: id}, function (data) {
                    var retValue = null;
                    if (data.code === "A00000" && data.data.result != null) {
                        retValue = data.data.result[0];
                        self.fillData(retValue);
                    } else {
                        self.fillNoData();
                    }
                });
            } else {
                self.fillNoData();
            }
        },

        fillData: function (element) {
            var self = this;
            for (var sginalBaseKey in element) {
                if (sginalBaseKey =="sginalServers") {
                    var sginalServer = element[sginalBaseKey];
                    $.each(sginalServer, function (n, value) {
                        if (value.serverType == 2) {
                            self.options.$container.find("input[name=id_" + value.serverType + "]").val(value.id);
                            self.options.$container.find("select[name=inputType_" + value.serverType + "]").val(value.inputType);
                            self.options.$container.find("input[name=inputIp_" + value.serverType + "]").val(value.inputIp);
                            self.options.$container.find("input[name=inputPort_" + value.serverType + "]").val(value.port);
                            self.options.$container.find("select[name=outputType_" + value.serverType + "]").val(value.outputType);
                            self.options.$container.find("input[name=outputIp_" + value.serverType + "]").val(value.outputIp);
                            self.options.$container.find("input[name=outputPort_" + value.serverType + "]").val(value.port);
                        } else if (value.serverType == 3) {
                            var $addndel = $("#addndel");
                            var $addBtn = $addndel.find("button[class='btn add blue-btn']");
                            if (value.sequence == 1) {
                            } else {
                                $addBtn.click();
                                $addBtn = $addndel.find("button[class='btn add blue-btn']");
                            }
                            $addBtn.parents(".form-group").find("input[name=id_" + value.serverType + "]").val(value.id);
                            $addBtn.parents(".form-group").find("select[name=outputType_" + value.serverType + "]").val(value.outputType);
                            $addBtn.parents(".form-group").find("input[name=outputIp_" + value.serverType + "]").val(value.outputIp);
                            $addBtn.parents(".form-group").find("input[name=outputPort_" + value.serverType + "]").val(value.port);
                        } else if (value.serverType == 4) {
                            self.options.$container.find("input[name=id_" + value.serverType + "]").val(value.id);
                            self.options.$container.find("select[name=outputType_" + value.serverType + "]").val(value.outputType);
                            self.options.$container.find("input[name=outputIp_" + value.serverType + "]").val(value.outputIp);
                            self.options.$container.find("input[name=outputPort_" + value.serverType + "]").val(value.port);
                            self.options.$container.find("select[name=ethNum_4]").val(value.ethNum);
                        }
                    });
                } else if (sginalBaseKey == "id"){
                    self.options.$container.find("input[name=sginalBaseId]").val(element[sginalBaseKey]);
                } else {
                    self.options.$container.find("input[name=" + sginalBaseKey + "]").val(element[sginalBaseKey]);
                }
            }
            $("input[name^=inputPort]").val(element["port"]);
            $("input[name^=outputPort]").val(element["port"]);
        },
        fillNoData: function () {
            var self = this;
        },

        bindEvent: function() {
            var self = this;
            var validator = self.getValidator();
            var $container = self.options.$container;
            var $submit = $container.find('#Submit');

            $container.find('input[name=port]').change(function() {
                $("input[name^=inputPort]").val($(this).val());
                $("input[name^=outputPort]").val($(this).val());
            });

            $addndel = $('#addndel').addndel({
                rowClass : 'form-group',
                addDecorator : function($newRow, $clickedRow) {
                    var order = $clickedRow.attr("order");
                    $newRow.attr("order", parseInt(order) + 1);
                    $newRow.find("input[name=outputPort_3]").val($("input[name=port]").val());
                    return true;
                },
                delDecorator : function($deletedRow) {
                  return true;
                }
              });

            $submit.on('click', function() {
                var _save = function(data) {
                    $(document).tips({
                        content: "页面提交中",
                        type: "loading"
                    });
                    if ($('#sginalBaseId').val() != "") {
                        self.edit(data);
                    } else {
                        self.add(data);
                    }
                };
				var success = validator.form();
                var data = self.getParam();

				if (success){
					_save(data);
				}

            });
        },

        getValidator: function() {
            var $container = this.options.$container;
            var $form = $container;
            var validator = Validator.getValidator($form, Sginal.Config.validator);

            return validator;
        },
        getParam: function() {
            var $container = this.options.$container;
            var self = this;
			var checkboxObj = null;
            var $elements = $.makeArray($container.prop('elements')).filter(function(item) {

				return true;
            });

			var checkboxVal = [];
            var name;
            var key;
			var params = {};
			var sginalServers = [];
            var server ={};
            var order = -1;
            var num = 0;
            $.each($elements, function() {
                name = this.name;
                if (name) {
                    if(name=='sginalBaseId' && $(this).val() != '') {
                        params['id'] = $(this).val();
                    } else if (name=='name' || name=='accessServerIp' || name=='port'){
                        params[name] = $.trim($(this).val());
                    } else if (/^[a-zA-Z]+_[2-4]$/.test(name)){
                        var array = name.split("_");
                        var index = array[1]-2;
                        if (array[1] == '3') {
                            if (order == -1) {
                                order = $(this).parents(".form-group").attr("order");
                            } else if (order != $(this).parents(".form-group").attr("order")){
                                order = $(this).parents(".form-group").attr("order");
                                num += 1;
                            }
                        }
                        index += num;
                        if (typeof(sginalServers[index]) == 'undefined') {
                            sginalServers[index]={};
                        }
                        if (array[0] == 'id' && ($(this).val() == '' || array[1] == '3')) {
                        } else if (array[0] == 'inputPort' || array[0] == 'outputPort') {
                            sginalServers[index]['port'] = $.trim($(this).val());
                        } else {
                            sginalServers[index][array[0]] = $.trim($(this).val());
                        }
                        sginalServers[index]['serverType']=array[1];
                        sginalServers[index]['sequence']=index;

                    }
                }
            });
            params['author'] = $("div.user a.name").html();
            params['sginalServers']=sginalServers;
            return {entity : JSON.stringify(params) };
        },
        add: function(data) {
            this.dao.add(data, this.onSave);
        },
        edit: function(data) {
            this.dao.edit(data, this.onSave);
        },

        onSave: function(json) {
            if (json.code == 'A00000') {
                var id = $("input[name=sginalBaseId]").val();
                var url = "";
                if (id != null) {
                    url = '/epg/sginal_home.html?id=' + id;
                } else {
                    url = '/epg/sginal_home.html';
                }

                setTimeout(function() {
                    window.location.href = url;
                }, 2000);
                var html = '操作成功，系统将在两秒后跳转到节目页面,<a href="' + url + '" target="_self">立即跳转</a>';
                $(document).tips({
                    content: html,
                    type: "loading"
                });
            } else {
                $(document).tips({
                    content: json.msg,
                    type: "error"
                });
            }

        },
        initSuggest: function() {
            var serverIpSuggest = {
                options: {
                    source: "/api/server/list",
                    method: "post",
                    multiple: false,
                    parseValue: function () {
                        var val = this.element.val(),
                            ret = []
                        return ret;
                    },
                    select: function (event, object) {
                        var item = object.item;
                        $(event.target).val(item.serverIp);
                        var server = $(event.target).attr("server");
                        $("#" + server + "Port").val(item.serverPort);
                        return false;
                    },
                    getParam: function (term) {
                        var requestData = {serverIp: term,status: 1,server_type: 2, timeSign: new Date().getTime()};
                        return requestData;
                    },

                    process: function (json) {
                        var ret = [],
                            self = this,
                            options = self.options,
                            itemData = null;
                        var data = null;
                        if (json == null) {
                            return [];
                        }
                        if (json.code === "A00000") {
                            data = $.isArray(json) ? json : json.data.result;
                        }
                        if (!data) {
                            return [];
                        }
                        $.map(data, function (item) {
                            itemData = {};
                            itemData[options.valueKey] = item["id"];
                            itemData[options.labelKey] = item["serverIp"];
                            itemData["serverIp"] = item["serverIp"];
                            itemData["serverPort"] = item["serverPort"];
                            itemData["province"] = item["province"] || "";
                            itemData["city"] = item["city"] || "";
                            itemData["remark"] = item["remark"];
                            ret.push(itemData);
                        });
                        return ret;
                    },

                    template: function (item) {
                        var formatArr = [];
                        formatArr.push('<span class="contract-width100">' + item["serverIp"] + '</span>');
                        formatArr.push('<span class="contract-width100">' + item["serverPort"] + '</span>');
                        formatArr.push('<span class="contract-width80">' + item["province"] + '</span>');
                        formatArr.push('<span class="contract-width80">' + item["city"] + '</span>');
                        formatArr.push('<span class="contract-width300">' + item["remark"] + '</span>');
                        return '<div class="contract-item" >' + formatArr.join("") + '</div>';
                    },
                    header: '<div class="contract-item" >' +
                        '<span class="contract-width100">服务器IP</span>' +
                        '<span class="contract-width100">服务器端口号</span>' +
                        '<span class="contract-width80">省份</span>' +
                        '<span class="contract-width80">市区</span>' +
                        '<span class="contract-width300">描述</span>'
                }
            };

            //$("input[name=fgIp]").suggest(serverIpSuggest.options);
            //$("input[name=idcIp]").suggest(serverIpSuggest.options);
        }
    };

});
